


function gcommunicate.Initialize()
	--first we need to make a connection 
	gcommunicate.Connect()
	if !gdatabase.CheckForConnection(gcommunicate.DB) then 
		timer.Create( "gcommreconnecter", gcommunicate.config.reconnecttime, 0, gcommunicate.Initialize)
		return 
	else
		if timer.IsTimer("gcommreconnecter") then
			timer.Destroy("gcommreconnecter")
		end
	end
	
	
	--Inits the connection
	gcommunicate.lib.connectinit()
	
	--Add the Gdatabase Hooks
	gdatabase.HookAdd("connect", "gcommunicate_connect", gcommunicate.lib.connectinit, gcommunicate.DB)
	gdatabase.HookAdd("disconnect", "gcommunicate_disconnect", gcommunicate.lib.disconnectinit, gcommunicate.DB)
	gdatabase.HookAdd("shutdown", "gcommunicate_shutdown", gcommunicate.lib.shutdown, gcommunicate.DB)
	
end
hook.Add("Initialize", "gcommunicateInitialize", gcommunicate.Initialize)

--Establishes a connection to the database. Returns true if connected, false if not.
function gcommunicate.Connect()
	gcommunicate.DB = gdatabase.MakeConnection(gcommunicate.config.databasehost, gcommunicate.config.databaseun, gcommunicate.config.databasepw, gcommunicate.config.databasename, gcommunicate.config.gdatabasesettings)
	
	if( gcommunicate.DB == false ) then
		gcommunicate.DB = 0
		return false
	else
		return true
	end
	
end

--PLAYER INITIAL SPAWN THREAD FUNCTIONS!!
function gcommunicate.PlayerInitialSpawn( ply )
	local uid = ply:UserID()
	local steamid = ply:SteamID()
	local name = gdatabase.CleanString(gcommunicate.DB, ply:GetName())
	local ip = ply:IPAddress()
	
	if steamid == "STEAM_ID_LAN" then
		steamid = ip
	end
	
	local query = gdatabase.Query("SELECT id FROM `clients` WHERE steamid = \'"..steamid.."\';", gcommunicate.DB)


	if query[1] then
		-- Hey, the player has been here before, we'll just update.
		query = gdatabase.Query("UPDATE `clients` SET ip=\'"..ip.."\', name=\'"..name.."\', isonline=1, serverid=\'"..gcommunicate.serverid.."\',  lastseen=UNIX_TIMESTAMP() WHERE steamid=\'"..steamid.."\';", gcommunicate.DB)
	else
		-- This person hasn't been here before, insert them into the database!
		query = gdatabase.Query("INSERT INTO `clients` ( `name`, `steamid`, `ip`, `isonline`, `lastseen`, `serverid` ) VALUES ( \'"..name.."\', \'"..steamid.."\', \'"..ip.."\', \'1\', UNIX_TIMESTAMP(), \'"..gcommunicate.serverid.."\' );", gcommunicate.DB)
		
	end
	
	local query = gdatabase.Query("INSERT INTO `chat` ( `serverid` , `playerid` , `pname` , `time` , `chat` ) VALUES ( \'"..gcommunicate.serverid.."\', \'0\', \'Console\', UNIX_TIMESTAMP() , \'"..name.." has connected to "..gcommunicate.config.servername.."\' );", gcommunicate.DB)
	
	local query = gdatabase.Query("SELECT	id FROM `clients` WHERE steamid = \'"..steamid.."\';", gcommunicate.DB)
	ply.gcommunicateid = query[1][1] or 0
end
 



function gcommunicate.PlayerDisconnected(ply)
	if !gdatabase.CheckForConnection(gcommunicate.DB) then return end
	
	local steamid = ply:SteamID()
	local name = gdatabase.CleanString(gcommunicate.DB, ply:GetName())
	
	gdatabase.Query("UPDATE `clients` SET name=\'"..name.."\', isonline=0, lastseen=UNIX_TIMESTAMP() WHERE steamid=\'"..steamid.."\';", gcommunicate.DB)
	gdatabase.Query("INSERT INTO `chat` ( `serverid` , `playerid` , `pname`, `time` , `chat` ) VALUES ( \'"..gcommunicate.serverid.."\', \'0\', \'Console\', UNIX_TIMESTAMP() , \'"..name.." has disconnected from "..gcommunicate.config.servername.."\' );", gcommunicate.DB)
end



function gcommunicate.PlayerSay( ply, text, teamsay )
	local pid = ply.gcommunicateid
	local pname = gdatabase.CleanString(gcommunicate.DB, ply:GetName())
	local sid = gcommunicate.serverid
	
	--GLOBALRP FILTER--
	if string.find(string.Left(text, 2), "//") then
		text = string.gsub(text,"//","",1)
	end
	
	if string.find(string.Left(text, 1), "/") then
		text = string.gsub(text,"/","",1)
	end
	--END--
	
	text = gdatabase.CleanString(gcommunicate.DB, text)
	
	gdatabase.threadedquery("INSERT INTO `chat` ( `serverid` , `playerid` , `pname` , `time` , `chat` ) VALUES ( \'"..sid.."\', \'"..pid.."\', \'"..pname.."\', UNIX_TIMESTAMP() , \'"..text.."\' );", gcommunicate.DB, gcommunicate.lib.generalthreadcallback)
end



--START OF MESSAGE THREADS
function gcommunicate.Messages( )
	if !gdatabase.CheckForConnection(gcommunicate.DB) then return end
	gdatabase.threadedquery("SELECT chat.id, chat.serverid, chat.playerid, chat.pname, chat.time, chat.chat, servers.name FROM `chat`, `servers` WHERE chat.id > " .. gcommunicate.maxid .. " AND servers.name != \'" .. gcommunicate.config.servername .. "\' AND servers.id = chat.serverid ORDER BY chat.id;", gcommunicate.DB, gcommunicate.MessagesThread1)
end	

function gcommunicate.MessagesThread1(query)
	--PrintTable(query)
	if (query == 0) then return end
	--only update the id if there is information, this stops timeshifting
	if query[1] != nil then
		gcommunicate.maxid = query[table.maxn(query)][1]
	end
	
	for k,v in pairs(query) do
		--Msg( v[4] .. "(".. v[7] .. ")" ..": " .. v[6] .. "\n")
		if v[2] != gcommunicate.serverid and v[7] != gcommunicate.config.servername then
			-- local serverid = v[2]
			-- local playerid = v[3]
			-- local pname = v[4]
			-- local timestamp = v[5]
			-- local chat = v[6]
		
			for _,x in pairs(player.GetAll()) do
				if v[3] != 0 then
					x:PrintMessage( HUD_PRINTTALK, v[4] .. "(".. v[7] .. ")" ..": " .. v[6] )
					--x:PrintMessage( HUD_PRINTNOTIFY, v[4] .. "(".. v[2] .. ")" ..": " .. v[6] ) it prints twice
				else
					x:PrintMessage( HUD_PRINTTALK, v[6] )
					--x:PrintMessage( HUD_PRINTNOTIFY, v[6] ) it prints twice
				end
			end
		end
	end



end
timer.Create("gcommunicateMessages",gcommunicate.config.updatetime,0,gcommunicate.Messages)
--END MESSAGE THREADS





